﻿using System;
using System.Globalization;
using System.Linq;
using System.Windows;
using System.Windows.Navigation;
using CuteRibs.D3Armory.Models;
using CuteRibs.D3Armory.Resources;
using CuteRibs.D3Armory.ViewModels;
using CuteRibs.MVVMLib;
using Microsoft.Live;
using Microsoft.Phone.Tasks;

namespace CuteRibs.D3Armory.Views
{
	public partial class ProfilesPage : PageBase
	{
		private ProfilesPageViewModel myViewModel;

		public ProfilesPageViewModel MyViewModel
		{
			get
			{
				if (this.myViewModel == null)
				{
					this.myViewModel = (ProfilesPageViewModel)this.DataContext;
				}

				return this.myViewModel;
			}
		}

		public ProfilesPage()
			: base()
		{
			InitializeComponent();

			this.Loaded += delegate
			{
				this.AppButtons[0].Text = AppRes.btnAdd;
				this.AppButtons[1].Text = AppRes.btnServer;
				this.AppButtons[2].Text = AppRes.btnHelp;
				this.AppMenus[0].Text = AppRes.mnuRate;
				this.AppMenus[1].Text = AppRes.mnuFeedback;
				this.AppMenus[2].Text = AppRes.mnuShare;
				this.AppMenus[3].Text = AppRes.mnuClear;
#if !FREE
				this.AppMenus[4].Text = AppRes.mnuUpload;
				this.AppMenus[5].Text = AppRes.mnuDownload;

				this.AppMenus[4].IsEnabled =
					this.AppMenus[5].IsEnabled = true;
#endif

				this.AppButtons[2].IsEnabled = false;
			};
		}

		private void RefreshData()
		{
			this.MyViewModel.ProfileGroups = null;
			this.MyViewModel.ProfileGroups = App.CurrentProfiles.OrderBy(p => p.BattleTag).GroupBy(p => p.Realm).OrderBy(g => g.Key).Select(g => new ProfileGroup(g.Key, g)).ToList();
		}

		private async void BackupProfiles()
		{
			this.MyViewModel.ShowProgressBar = true;

			try
			{
				bool result = await App.BackupToCloud();

				if (result)
				{
					App.ShowAlert(AppRes.MsgProfileBackupFinished);
				}
				else
				{
					App.ShowAlert(AppRes.MsgLiveBackupFailed);
				}
			}
			catch (Exception ex)
			{
				if (ex is LiveAuthException) { }
				else
				{
					App.ShowError(ex);
				}
			}

			this.MyViewModel.ShowProgressBar = false;
		}

		private async void RestoreProfiles()
		{
			this.MyViewModel.ShowProgressBar = true;

			try
			{
				if (await App.RestoreFromCloud())
				{
					this.RefreshData();
				}
				else
				{
					App.ShowAlert(AppRes.MsgLiveCannotFindBackup);
				}
			}
			catch (Exception ex)
			{
				if (ex is LiveAuthException) { }
				else
				{
					App.ShowError(ex);
				}
			}

			this.MyViewModel.ShowProgressBar = false;
		}

		protected override void OnNavigatedTo(NavigationEventArgs e)
		{
			if (!App.IsSplashScreenLoaded)
			{
				App.IsSplashScreenLoaded = true;
				this.NavigationService.Navigate("/Views/SplashScreenPage.xaml");
				return;
			}

			base.OnNavigatedTo(e);

			this.Dispatcher.BeginInvoke(delegate
			{
				this.RefreshData();
			});
		}

		private void Grid_Tap(object sender, System.Windows.Input.GestureEventArgs e)
		{
			var profile = (sender as FrameworkElement).DataContext as ProfileBrief;
			this.NavigationService.Navigate(string.Format("/Views/ProfilePage.xaml?Region={0}&BattleTag={1}", profile.Realm.Region, profile.BattleTag.Tag));
		}

		private void mnuDelete_Click(object sender, EventArgs e)
		{
			var control = sender as FrameworkElement;
			var profile = control.DataContext as ProfileBrief;

			this.Dispatcher.BeginInvoke(delegate
			{
				App.DeleteProfile(profile.Realm, profile.BattleTag.Tag);
				this.RefreshData();
			});
		}

		private void btnAdd_Click(object sender, EventArgs e)
		{
			this.NavigationService.Navigate("/Views/ProfileAddPage.xaml");
		}

		private void btnStatus_Click(object sender, EventArgs e)
		{
			this.NavigationService.Navigate("/Views/RealmStatusPage.xaml");
		}

		private void btnAbout_Click(object sender, EventArgs e)
		{
			//this.NavigationService.Navigate("/Views/HeroPage.xaml?Region={0}&BattleTag={1}&Hero={2}", "Asia", "Cuteribs-1554", "7782993");
		}

		private void btnRate_Click(object sender, EventArgs e)
		{
			new MarketplaceReviewTask().Show();
		}

		private void btnFeedback_Click(object sender, EventArgs e)
		{
			EmailComposeTask task = new EmailComposeTask();
			task.To = "ericfine2012@live.com";
			task.Bcc = "48657539@qq.com";
			task.Subject = string.Format("{0} ({1}) Feedback", AppRes.AppName, CultureInfo.CurrentCulture.Name);
			task.Show();
		}

		private void btnShare_Click(object sender, EventArgs e)
		{
			ShareLinkTask task = new ShareLinkTask();
			task.LinkUri = new Uri("http://www.windowsphone.com/s?appid=1be83bf5-d986-46a3-bbea-787cc2596f2c", UriKind.Absolute);
			task.Title = AppRes.MsgCheckOutThisApp;
			task.Message = string.Format(AppRes.MsgCheckOutThisAppContent, AppRes.AppName);
			task.Show();
		}

		private void btnClear_Click(object sender, EventArgs e)
		{
			if (App.ShowConfirm(AppRes.MsgClearCache) == MessageBoxResult.OK)
			{
				App.ClearCache();
			}
		}

		private void btnUpload_Click(object sender, EventArgs e)
		{
#if !FREE
			this.BackupProfiles();
#endif
		}

		private void btnDownload_Click(object sender, EventArgs e)
		{
#if !FREE
			this.RestoreProfiles();
#endif
		}
	}
}